package com.echat.elocation.connect;


import com.echat.elocation.constant.ProtocolConstant;
import com.echat.elocation.event.ConnectionEvent;
import com.echat.elocation.event.HeartbeatEvent;
import com.echat.elocation.protocol.code.MsgDecoder;
import com.echat.elocation.protocol.entity.PackageMsg;
import com.echat.elocation.protocol.entity.receive.RegisterRespMsg;
import com.echat.elocation.protocol.entity.receive.ServerCommonRespMsg;
import com.echat.elocation.protocol.entity.receive.TextMsgIssuedRespMsg;
import com.echat.elocation.util.HexStringUtils;
import com.echat.elocation.util.Logger;

import org.greenrobot.eventbus.EventBus;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author lihao
 * @date 2018/7/11 9:47
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<Object> {

    private static final String TAG = "NettyClientHandler";

    private MsgDecoder mDecoder;

    public NettyClientHandler() {
        this.mDecoder = new MsgDecoder();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Logger.i(TAG, "channelActive: ------连接成功------");
        EventBus.getDefault().post(new ConnectionEvent(ConnectionEvent.CONNECT_SUCCESS));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Logger.i(TAG, "channelInactive: ------连接断开------");
        NettyClient.getInstance().setConnect(false);
        EventBus.getDefault().post(new ConnectionEvent(ConnectionEvent.CONNECT_CLOSED));
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            EventBus.getDefault().post(new HeartbeatEvent(((IdleStateEvent) evt).state()));
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        if (buf.readableBytes() <= 0) {
            return;
        }
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        Logger.i(TAG, "Read message: " + HexStringUtils.toHexString(data).replaceAll("(.{2})", "$1 "));

        PackageMsg pkg = mDecoder.bytesToPackageMsg(data);
        processMsg(pkg);
    }

    private void processMsg(PackageMsg pkg) {
        PackageMsg.MsgHeader header = pkg.getMsgHeader();
        switch (header.getMsgId()) {
            case ProtocolConstant.cmd_terminal_register_resp:
                RegisterRespMsg registerRespMsg = mDecoder.toRegisterRepMsg(pkg);
                EventBus.getDefault().post(registerRespMsg);
                break;
            case ProtocolConstant.cmd_common_resp:
                ServerCommonRespMsg commonRepMsg = mDecoder.toServerCommonRepMsg(pkg);
                EventBus.getDefault().post(commonRepMsg);
                break;
            case ProtocolConstant.cmd_text_message_issued_resp:
                TextMsgIssuedRespMsg textMsgIssuedRespMsg = mDecoder.toTextMsgIssuedRepMsg(pkg);
                EventBus.getDefault().post(textMsgIssuedRespMsg);
                break;
            default:
                break;
        }
    }
}
